<template>
    <div class="todolist">
        <input type="text" v-model="inputValue">
        <button @click="onCreate">新增</button>
        <button @click="onSearch">查询</button>
        <ul>
            <li
                v-for="item in showingList"
                :key="item.id"
            >
                <input v-if="editingId === item.id" type="text" v-model="editingValue">
                <span v-else>{{ item.value }}</span>
                
                <button v-if="editingId === item.id" @click="() => onEditOk(item.id)">确认</button>
                <button v-else @click="() => onEdit(item)">修改</button>

                <button @click="() => onDelete(item.id)">删除</button>
            </li>
        </ul>
    </div>
</template>

<script>
import {
    mapState,
    mapMutations,
} from 'vuex';

let currentId = 0;

export default {
    data () {
        return {
            inputValue: '',
            editingValue: '',
            editingId: -1,
        };
    },
    computed: {
        ...mapState('todolist', ['list', 'showingList']),
    },
    methods: {
        ...mapMutations('todolist', ['SET_LIST', 'SET_SHOWING_LIST']),
        onCreate () {
            this.SET_LIST(this.list.concat({
                id: currentId++,
                value: this.inputValue,
            }));
            this.inputValue = '';
        },
        onDelete (id) {
            this.SET_LIST(this.list.filter((item) => id !== item.id));
        },
        onSearch () {
            this.SET_SHOWING_LIST(this.list.filter(item => item.value.includes(this.inputValue)));
        },
        onEdit (item) {
            this.editingId = item.id;
            this.editingValue = item.value;
        },
        onEditOk (id) {
            this.editingId = -1;
            this.SET_LIST(this.list.map(item => {
                if (item.id === id) {
                    return {
                        ...item,
                        value: this.editingValue,
                    };
                }
                return item;
            }));
        },
    },
}
</script>
